package m.framework.controller;

import m.framework.ClassType;
import m.framework.dao.selector.PageRecord;
import m.framework.dao.selector.Query;
import m.framework.service.BaseService;
import m.framework.utils.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author ming
 * @date 2014年2月19日下午12:13:43
 */
public class BaseController implements UserHolder {
	private static Logger log = LoggerFactory.getLogger(BaseController.class);
	public static final int DEFAULT_REWS_PERPAGE = 150;
	private static ThreadLocal<CurrentUser> userHolder = new ThreadLocal<CurrentUser>();
	
	@RequestMapping
	public void test() {

	}
	
	public CurrentUser getUser() {
		return userHolder.get();
	}

	public void setUser(CurrentUser user) {
		userHolder.set(user);
	}

	protected PageRecord queryContinue(PageRecord pageRecord){
		Object query = pageRecord.getQuery();
		BaseService bs = getService(BaseService.class);
		Query q = (Query) query;
		q.setOrder(pageRecord.getOrderField(), pageRecord.getOrderType());
		return bs.queryPage(q, pageRecord.getPageNo(), pageRecord.getRowsPerPage());
	}
	
	//获得service如果class为null则返回和model名称相同的service
	protected <T extends BaseService> T getService(Class<? extends BaseService> cs) {
		if (cs == null) {
			if(this instanceof BaseController){
				cs=ClassType.controller.getOrtherType(this.getClass(), ClassType.service);
			}else{
				return (T)BaseService.getDefault();
			}
		}
		return (T) BaseService.getService(cs);
	}
	
	
	protected BaseService defultService(){
		return BaseService.getDefault();
	}
	

	/**对应url前缀名称*/
	public String getName() {
		return StringUtil.firstLower(ClassType.controller.modelName(this.getClass()));
	}
}
